﻿using System.Linq;
using System.Web.Mvc;
using Church.Common;
using Church.Entities;
using Church.Models.Shared;
using Church.Resources;
using MvcContrib;

namespace Church.Controllers
{
	public class HomeController : Controller
	{
		#region Actions

		public ActionResult Index()
		{
			return View();
		}

		public ActionResult Puzzles()
		{
			var model = new PuzzlesModel
			{
				IsShowBackLink = false
			};
			FillPuzzlesModel(model);
			return View(model);
		}

		public ActionResult History()
		{
			var path = HttpContext.Server.MapPath(AppConfig.HistoryInformationDataFilePath);
			var model = AppContext.XmlSerializerService.Deserialize<Information>(path);
			return View(model);
		}

		public ActionResult Specifications()
		{
			var path = HttpContext.Server.MapPath(AppConfig.ChurchSpecificationDataFilePath);
			var model = AppContext.XmlSerializerService.Deserialize<Information>(path);
			return View(model);
		}

		public ActionResult Information(Information model)
		{
			return View(model ?? new Information());
		}

		public ActionResult ContactUs()
		{
			return View();
		}

		public ActionResult Schedule()
		{
			var model = AppContext.ServiceFactory.ScheduleService.GetDays();
			if (model == null)
				return this.RedirectToAction(a => a.Index());
			return View(model);
		}

		public ActionResult Calendar()
		{
			return View();
		}

		#endregion

		#region Internal Implementation

		private void FillPuzzlesModel(PuzzlesModel model)
		{
			if (model != null)
			{
				var path = HttpContext.Server.MapPath(AppConfig.MainMenuDataFilePath);
				var data = AppContext.XmlSerializerService.Deserialize<MenuCollection>(path);
				if (data != null && data.MenuItems != null && data.MenuItems.Any())
				{
					for (var item = 0; item < data.MenuItems.Count && item < Constants.DEFAULT_COUNT_PUZZLES; item++)
					{
						model.Puzzles.ElementAt(item).Description = data.MenuItems.ElementAt(item).Description;
						model.Puzzles.ElementAt(item).Header = data.MenuItems.ElementAt(item).Header;
						model.Puzzles.ElementAt(item).ImageUrl = data.MenuItems.ElementAt(item).ImageUrl;
						model.Puzzles.ElementAt(item).Url =
							new UrlHelper(Request.RequestContext).Action(data.MenuItems.ElementAt(item).Action,
								data.MenuItems.ElementAt(item).Controller);
					}
					model.FooterHelp = data.FooterHelp;
				}
			}
		}

		#endregion
	}
}
